package api

import (
	"buding-ai/internal/web/response"
	"buding-ai/pkg/config"
	"github.com/gin-gonic/gin"
	sts "github.com/tencentyun/qcloud-cos-sts-sdk/go"
	"time"
)

type CosApi struct {
	router *gin.RouterGroup
	BaseApi
}

func NewCosApi(router *gin.RouterGroup) *CosApi {
	api := &CosApi{
		router: router,
	}
	router.GET("/upload", api.Upload)
	return api
}

func (api *CosApi) Upload(ctx *gin.Context) {
	// https://github.com/tencentyun/qcloud-cos-sts-sdk/blob/master/go/example/sts_demo.go
	//https://cloud.tencent.com/document/product/436/9067
	// 配置信息
	cfg := config.GetConfig().Cos

	directory := time.Now().Format("20060102")

	// 创建STS客户端
	c := sts.NewClient(cfg.SecretID, cfg.SecretKey, nil)

	// 配置临时密钥选项
	opt := &sts.CredentialOptions{
		DurationSeconds: int64(time.Hour.Seconds()), // 临时密钥有效期1小时
		Region:          cfg.Region,
		Policy: &sts.CredentialPolicy{
			Statement: []sts.CredentialPolicyStatement{
				{
					// 密钥的权限列表
					Action: []string{
						// 简单上传
						"name/cos:PostObject",
						"name/cos:PutObject",
						// 分片上传
						"name/cos:InitiateMultipartUpload",
						"name/cos:ListMultipartUploads",
						"name/cos:ListParts",
						"name/cos:UploadPart",
						"name/cos:CompleteMultipartUpload",
					},
					Effect: "allow",
					Resource: []string{
						"qcs::cos:" + cfg.Region + ":uid/" + cfg.AppID + ":" + cfg.Bucket + "/" + directory + "*",
					},
				},
			},
		},
	}

	// 请求临时密钥
	res, err := c.GetCredential(opt)
	if err != nil {
		response.InternalError(ctx, "获取cos授权失败:", err)
		return
	}
	response.SuccessWithData(ctx, response.COSCredentialVO{
		TmpSecretID:  res.Credentials.TmpSecretID,
		TmpSecretKey: res.Credentials.TmpSecretKey,
		SessionToken: res.Credentials.SessionToken,
		Region:       cfg.Region,
		Bucket:       cfg.Bucket,
		StartTime:    time.Now().Unix(),
		ExpiredTime:  res.ExpiredTime,
		Directory:    directory,
	})
}
